package com.cz.nongyetongv5.activity;

import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

import com.cz.nongyetongv5.adapter.config.CommonConstants;
import com.cz.nongyetongv5.adapter.dao.DatabaseHelper;
import com.cz.nongyetongv5.bean.Delbean;
import com.cz.nongyetongv5.bean.User;
import com.cz.nongyetongv5.custom.dialog.CheckDialog;
import com.cz.nongyetongv5.custom.dialog.CustomDialog;
import com.cz.nongyetongv5.custom.dialog.DownloadDialog;
import com.cz.nongyetongv5.utils.Session;
import com.cz.nongyetongv5.utils.UpdateDateUtilEx;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SyncActivity extends FragmentActivity {


    /**
     * 登陆等待的对话框
     */
    private CustomDialog waitUserLoginDialog = null;


    /**
     * 验证用户的handler
     */
    private Handler validateUser;


    private DatabaseHelper db = null;
    User user;

    public DownloadDialog downloadWaitDialog = null;
    public CheckDialog checkDialog = null;
    private static final int SHOW = 100;
    private static final int HIDE = 101;
    private static final int SYNCCOMP = 200;
    private static final int SHOWPLANCHECK = 1100;
    private static final int SYNCPLANCOMP = 1200;

    private static final int SHOWSUM = 3100;


    protected void ionCreate(Bundle savedInstanceState) {


        //registSreenStatusReceiver();
        db = new DatabaseHelper(this, CommonConstants.DBNAME, null,
                CommonConstants.DATABASE_VERSION);


        user = (User) getIntent().getSerializableExtra("user");

        validateUser = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case SHOW:
                        if (downloadWaitDialog != null && downloadWaitDialog.isShowing())
                            downloadWaitDialog.dismiss();
                        if (checkDialog != null && checkDialog.isShowing()) {
                            checkDialog.dismiss();
                            checkDialog = null;
                        }
                        if (waitUserLoginDialog != null && waitUserLoginDialog.isShowing()) {
                            waitUserLoginDialog.dismiss();
                            waitUserLoginDialog = null;
                        }
                        waitUserLoginDialog = new CustomDialog(SyncActivity.this);
                        waitUserLoginDialog.setWidthPercent(0.6F);
                        BarBean data = (BarBean) msg.obj;
                        waitUserLoginDialog.setMessage(data.msg);
                        waitUserLoginDialog.show();
                        break;
                    case SHOWSUM:
                        if (downloadWaitDialog != null && downloadWaitDialog.isShowing())
                            downloadWaitDialog.dismiss();
                        if (checkDialog != null && checkDialog.isShowing()) {
                            checkDialog.dismiss();
                            checkDialog = null;
                        }
                        if (waitUserLoginDialog != null && waitUserLoginDialog.isShowing()) {
                            waitUserLoginDialog.dismiss();
                            waitUserLoginDialog = null;
                        }
                        waitUserLoginDialog = new CustomDialog(SyncActivity.this);
                        waitUserLoginDialog.setWidthPercent(0.6F);
                        waitUserLoginDialog.setMessage("正在分析数据,请稍后");
                        waitUserLoginDialog.show();
                        break;
                    case HIDE:
                        if (downloadWaitDialog != null && downloadWaitDialog.isShowing())
                            downloadWaitDialog.dismiss();
                        if (waitUserLoginDialog != null && waitUserLoginDialog.isShowing()) {
                            waitUserLoginDialog.dismiss();
                            waitUserLoginDialog = null;
                        }
                        break;
                    case BARVAL:
                        //					 BarBean data=(BarBean)msg.obj;
                        //					 downloadWaitDialog.show();
                        //					 downloadWaitDialog.setMessage(data.msg);
                        //					 downloadWaitDialog.bar.setProgress(data.val);
                        break;
                    case BARVAL2:
                        BarBean data2 = (BarBean) msg.obj;
                        downloadWaitDialog.show();
                        downloadWaitDialog.setMessage("基础数据更新中");
                        downloadWaitDialog.bar.setProgress(data2.val);
                        break;
                    case SYNCPLANCOMP:
                        if (downloadWaitDialog != null && downloadWaitDialog.isShowing())
                            downloadWaitDialog.dismiss();
                        if (checkDialog != null && checkDialog.isShowing()) {
                            checkDialog.dismiss();
                            checkDialog = null;
                        }
                        checkDialog = new CheckDialog(SyncActivity.this);
                        checkDialog.setWidthPercent(0.6F);
                        checkDialog.setMessage("计划任务更新完成");
                        checkDialog.setSingle("确定");
                        checkDialog.show();
                        break;
                    case SHOWPLANCHECK:
                        getPlans();
                        //					 if(downloadWaitDialog!=null&&downloadWaitDialog.isShowing())
                        //						 downloadWaitDialog.dismiss();
                        //
                        //					     if(waitUserLoginDialog!=null&&waitUserLoginDialog.isShowing())
                        //						 waitUserLoginDialog.dismiss();
                        //					     if(checkDialog!=null&&checkDialog.isShowing()){
                        //	                		checkDialog.dismiss();
                        //	                		checkDialog=null;
                        //	                	  }
                        //	                	  checkDialog=new CheckDialog(SyncActivity.this);
                        //	                	  checkDialog.setWidthPercent(0.6F);
                        //	                	  checkDialog.setMessage("计划任务有变化,请立即更新");
                        //	                	  checkDialog.setSingle("确定");
                        //	                	  checkDialog.setSingleListener(new OnClickListener(){
                        //                          @Override
                        //							public void onClick(View arg0) {
                        //                        	       getPlans();
                        //						 	}});
                        //
                        //	                	  checkDialog.show();
                        break;
                    case SYNCCOMP:

                        downloadWaitDialog.dismiss();
                        if (checkDialog != null && checkDialog.isShowing()) {
                            checkDialog.dismiss();
                            checkDialog = null;
                        }
                        checkDialog = new CheckDialog(SyncActivity.this);
                        checkDialog.setWidthPercent(0.6F);
                        checkDialog.setMessage("基础数据更新成功");
                        checkDialog.setSingle("确定");
                        checkDialog.setSingleListener(new OnClickListener() {
                            @Override
                            public void onClick(View arg0) {
                                checkDialog.dismiss();
                                // checkPlan();
                            }
                        });
                        checkDialog.show();
                        break;
                    case CHECKSYNC:
                        doLogin();
                        //                 	if(checkDialog!=null&&checkDialog.isShowing()){
                        //                		checkDialog.dismiss();
                        //                		checkDialog=null;
                        //                	 }
                        //                	  checkDialog=new CheckDialog(SyncActivity.this);
                        //                	  checkDialog.setWidthPercent(0.6F);
                        //                	  checkDialog.setSingleListener(new OnClickListener(){
                        //
                        //							@Override
                        //							public void onClick(View arg0) {
                        //								// TODO Auto-generated method stub
                        //								   Session session=new Session(SyncActivity.this,"doing");
                        //						            if(session.getString().equals("1"))
                        //								        sument2();
                        //						            else{
                        //						            	checkDialog.dismiss();
                        //						             }
                        //							}
                        //	                	  });
                        //                	   checkDialog.setOnActionClickListener(new OnClickListener(){
                        //                        @Override
                        //						public void onClick(View arg0) {
                        //                        	  checkDialog.dismiss();
                        //                        	  doLogin();
                        //
                        //						}
                        //                	 });
                        //                	  checkDialog.show();
                        break;


                }
            }
        };


        if (downloadWaitDialog != null && downloadWaitDialog.isShowing()) {
            downloadWaitDialog.dismiss();
            downloadWaitDialog = null;
        }
        downloadWaitDialog = new DownloadDialog(this);
        downloadWaitDialog.setWidthPercent(0.6F);
        downloadWaitDialog.setMessage("准备下载数据");

        Session session = new Session(SyncActivity.this, "doing");
        session.setString("0");

        /**DEV:160916**/
        check3();

    }


    //计算数据
    private JSONArray checkRegions = null;

    private void sument2() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                UpdateDateUtilEx dataUtil = new UpdateDateUtilEx(db,
                        SyncActivity.this, user);
                int sec = 0;
                int result = dataUtil.updateTown(sec);

                setMessage("数据分析中", 1, BARVAL);

                Log.d("rafe result", String.valueOf(result));
                setMessage("基础数据更新中", 90, BARVAL2);
                int tick = 90;
                while (result > 0 && sec < 16000) {
                    sec = sec + 1000;
                    tick++;
                    if (tick > 99)
                        tick = 99;
                    setMessage("基础数据更新中", tick, BARVAL2);
                    result = dataUtil.updateTown(sec);
                }

                setMessage("基础数据更新完成", 0, SYNCCOMP);


            }
        }).start();
    }

    private String getPlanDelTime() {

        SharedPreferences sharedPreferences = getSharedPreferences("deltime", MODE_PRIVATE);
        String name = sharedPreferences.getString("name", "");
        return name;
    }

    private void setPlanDelTime(String time) {
        SharedPreferences sharedPreferences = getSharedPreferences("deltime", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        //用putString的方法保存数据
        editor.putString("name", time);
        //提交当前数据
        editor.commit();
    }

    private JSONObject otherSync = new JSONObject();

    private void check3() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                UpdateDateUtilEx dataUtil = new UpdateDateUtilEx(db,
                        SyncActivity.this, user);
                checkRegions = dataUtil.check3(user.getKnowRegion());
                if (checkRegions != null && checkRegions.length() > 0) {
                    setMessage("", 1, HIDE);
                    setMessage("", 1, CHECKSYNC);
                } else {
                    setMessage("", 1, HIDE);
                    checkPlan();
                }


            }
        }).start();
    }

    private void check2() {
        setMessage("", 1, SHOWSUM);
        new Thread(new Runnable() {
            @Override
            public void run() {
                UpdateDateUtilEx dataUtil = new UpdateDateUtilEx(db,
                        SyncActivity.this, user);
                checkRegions = dataUtil.check2(user.getKnowRegion());
                if (checkRegions.length() > 0) {
                    setMessage("", 1, HIDE);
                    setMessage("", 1, CHECKSYNC);
                } else {
                    setMessage("", 1, HIDE);
                    check3();
                }
            }
        }).start();
    }

    public static final int BARVAL = 77;
    public static final int BARVAL2 = 67;
    public static final int CHECKSYNC = 78;
    public static final int CHECKOTHER = 79;

    public void setMessage(String msg, int val, int code) {

        Message m = new Message();
        m.what = code;
        BarBean ben = new BarBean();
        ben.msg = msg;
        ben.val = val;
        m.obj = ben;
        validateUser.sendMessage(m);
    }


    class BarBean {
        public BarBean() {
        }

        public int val = 1;
        public String msg = "";

    }
    // 处理登陆的方法


    private void doLogin() {
        Session session = new Session(SyncActivity.this, "doing");
        session.setString("1");
        // 处理获取用户信息的线程
        Thread userLoginThread = new Thread(new Runnable() {
            @Override
            public void run() {

                if (checkRegions == null || checkRegions.length() < 0) {
                    setMessage("未知错误", 0, HIDE);
                    return;
                }
                Log.d("rafe", "被检对象同步开始...");
                setMessage("正在同步被检对象信息", 1, BARVAL2);
                setMessage("正在同步被检对象信息", 1, BARVAL2);
                for (int i = 0; i < checkRegions.length(); i++) {
                    doOther(checkRegions.optJSONObject(i));
                }
                setMessage("正在同步被检对象信息", 90, BARVAL2);
                //   			  setMessage("正在校验受检对象数据",10,BARVAL);
                UpdateDateUtilEx dataUtil = new UpdateDateUtilEx(db, SyncActivity.this, user);
                dataUtil.checkBack(user.getKnowRegion());
                //   			  setMessage("校验受检对象数据完成",100,BARVAL);

                Log.d("rafe", "被检对象同步完成...");

                sument2();

            }


        });
        userLoginThread.start();

    }

    private int ticktick = 1;

    private void tickh() {

        ticktick++;
        if (ticktick > 90)
            ticktick = 90;
        setMessage("正在同步被检对象信息", ticktick, BARVAL2);

    }

    private void doOther(JSONObject da) {

        JSONArray params = db.querySyncOther(user.getKnowRegion());
        if (da != null) {

            if (da.optInt("ent_delete_status") == 1) {
                tickh();
                Log.d("checkdata_del", String.valueOf(user.getKnowRegion()));
                del_ent("清理受检对象信息", "BEIJIANDANWEI", params.optJSONObject(0));
                db.insertOrUpdateMobileSync(user.getKnowRegion(), "ENT_DELETETIME");
            }
            if (da.optInt("ent_add_status") == 1) {

                sync_ent(params.optJSONObject(0), "add", "下载受检对象信息", "ent_add_time");
                tickh();
                Log.d("checkdata_add", String.valueOf(user.getKnowRegion()));
                db.insertOrUpdateMobileSync(user.getKnowRegion(), "ENT_ADDTIME");
            }
            if (da.optInt("ent_modify_status") == 1) {
                sync_ent(params.optJSONObject(0), "modify", "更新受检对象信息", "ent_modify_time");
                tickh();
                Log.d("checkdata_mode", String.valueOf(user.getKnowRegion()));
                db.insertOrUpdateMobileSync(user.getKnowRegion(), "ENT_MODIFYTIME");
            }

            setMessage("更新中", 71, BARVAL2);
            if (da.optInt("department_add_status") == 1) {
                tickh();
                Log.d("rafe", "检查单位同步开始");
                sync_obj("JIANCHADANWEI", "add", "下载检查单位", "ADDTIME");
                Log.d("rafe", "检测单位同步完成...");
                db.insertOrUpdateMobileSync(user.getKnowRegion(), "DEPART_ADDTIME");
            }
            setMessage("更新中", 74, BARVAL2);
            if (da.optInt("department_modify_status") == 1) {
                tickh();
                Log.d("rafe", "检查单位更新开始");
                sync_obj("JIANCHADANWEI", "modify", "更新检查单位", "MODIFYTIME");
                Log.d("rafe", "检测单位更新完成...");
                db.insertOrUpdateMobileSync(user.getKnowRegion(), "DEPART_MODIFYTIME");
            }
            setMessage("更新中", 76, BARVAL2);
            if (da.optInt("department_delete_status") == 1) {
                tickh();
                del_ent("清理检查单位", "JIANCHADANWEI", null);
                db.insertOrUpdateMobileSync(user.getKnowRegion(), "DEPART_DELETETIME");
            }
            setMessage("更新中", 80, BARVAL2);
            if (da.optInt("detector_add_status") == 1) {
                tickh();
                Log.d("rafe", "抽样机构同步开始");
                sync_obj("CHOUYANJIGOU", "add", "下载抽样机构", "ADDTIME");
                Log.d("rafe", "抽样机构同步完成...");
                db.insertOrUpdateMobileSync(user.getKnowRegion(), "DETECTOR_ADDTIME");
            }
            setMessage("更新中", 82, BARVAL2);
            if (da.optInt("detector_modify_status") == 1) {
                tickh();
                Log.d("rafe", "抽样机构更新开始");
                sync_obj("CHOUYANJIGOU", "modify", "更新抽样机构", "MODIFYTIME");
                Log.d("rafe", "抽样机构更新完成...");
                db.insertOrUpdateMobileSync(user.getKnowRegion(), "DETECTOR_MODIFYTIME");

            }
            setMessage("更新中", 85, BARVAL2);
            if (da.optInt("detector_delete_status") == 1) {
                del_ent("清理抽样机构", "CHOUYANJIGOU", null);
                db.insertOrUpdateMobileSync(user.getKnowRegion(), "DETECTOR_DELETETIME");
                tickh();
            }
            setMessage("更新中", 87, BARVAL2);
            if (da.optInt("team_add_status") == 1) {
                tickh();
                Log.d("rafe", "监管人员同步开始");
                sync_obj("JIANGUANRENYUAN", "add", "下载监管人员", "ADDTIME");
                Log.d("rafe", "监管人员同步完成...");
                db.insertOrUpdateMobileSync(user.getKnowRegion(), "TEAM_ADDTIME");

            }
            setMessage("更新中", 89, BARVAL2);
            if (da.optInt("team_modify_status") == 1) {
                tickh();
                Log.d("rafe", "监管人员更新开始");
                sync_obj("JIANGUANRENYUAN", "modify", "更新监管人员", "MODIFYTIME");
                Log.d("rafe", "监管人员更新完成...");
                db.insertOrUpdateMobileSync(user.getKnowRegion(), "TEAM_MODIFYTIME");
            }
            setMessage("更新中", 91, BARVAL2);
            if (da.optInt("team_delete_status") == 1) {
                tickh();
                del_ent("清理监管人员", "JIANGUANRENYUAN", null);
                db.insertOrUpdateMobileSync(user.getKnowRegion(), "TEAM_DELETETIME");
            }
            setMessage("更新中", 93, BARVAL2);
            if (da.optInt("linkman_add_status") == 1) {
                Log.d("rafe", "监管人员简化同步开始");
                sync_obj("LINKMAN", "add", "下载联系人", "ADDTIME");
                Log.d("rafe", "监管人员简化位同步完成...");
                db.insertOrUpdateMobileSync(user.getKnowRegion(), "LINKMAN_ADDTIME");
            }
            setMessage("更新中", 95, BARVAL2);
            if (da.optInt("linkman_modify_status") == 1) {
                tickh();

                Log.d("rafe", "监管人员简化同步开始");
                sync_obj("LINKMAN", "modify", "更新联系人", "MODIFYTIME");
                Log.d("rafe", "监管人员简化位同步完成...");
                db.insertOrUpdateMobileSync(user.getKnowRegion(), "LINKMAN_MODIFYTIME");
            }
            setMessage("更新中", 97, BARVAL2);
            if (da.optInt("linkman_delete_status") == 1) {
                del_ent("清理联系人", "LINKMAN", null);
                db.insertOrUpdateMobileSync(user.getKnowRegion(), "LINKMAN_DELETETIME");
            }

        }


    }

    private void sync_obj(String table, String opt, String msg, String timefield) {
        UpdateDateUtilEx dataUtil = new UpdateDateUtilEx(db,
                SyncActivity.this, user);
        String maxTime = db.queryMaxMotifyTime(table, timefield, user.getKnowRegion());
        //测试移除
        maxTime = "2015-09-10 12:00:00";

        maxTime = maxTime.replaceAll(" ", "%20");

        Log.d("rafe", table + "   " + maxTime);
        setMessage("正在" + msg + "信息 ", 0, BARVAL);
        int start = 0;
        int sum = dataUtil.sumAdd(table, start, maxTime, user.getKnowRegion(), opt);
        if (sum > 0) {
            while (start < sum) {
                start += 20;
                int bar = (int) (((double) start / (double) sum) * 100);
                if (bar > 100) {
                    bar = 100;
                }
                setMessage("正在" + msg + "信息 :" + bar + "%", bar, BARVAL);
                if (dataUtil.sumAdd(table, start, maxTime, user.getKnowRegion(), opt) < 0) {
                    Log.d("rafe", msg + "异常退出");
                    break;
                }
            }
            setMessage(msg + "信息完成", 100, BARVAL);

        }

    }

    private void sync_obj2(String table, String opt, String msg, String timefield) {
        UpdateDateUtilEx dataUtil = new UpdateDateUtilEx(db,
                SyncActivity.this, user);
        String maxTime = db.queryMaxMotifyTime(table, timefield, user.getKnowRegion());
        //测试移除
        maxTime = "2015-09-10 12:00:00";

        maxTime = maxTime.replaceAll(" ", "%20");

        Log.d("rafe", table + "   " + maxTime);
        setMessage("正在" + msg + "信息 ", 0, BARVAL);
        int start = 0;
        int sum = dataUtil.sumAdd(table, start, maxTime, user.getKnowRegion(), opt);
        if (sum > 0) {
            while (start < sum) {
                start += 20;
                int bar = (int) (((double) start / (double) sum) * 100);
                if (bar > 100) {
                    bar = 100;
                }
                setMessage("正在" + msg + "信息 :" + bar + "%", bar, BARVAL);
                if (dataUtil.sumAdd(table, start, maxTime, user.getKnowRegion(), opt) < 0) {
                    Log.d("rafe", msg + "异常退出");
                    break;
                }
            }
            setMessage(msg + "信息完成", 100, BARVAL);
        }

    }


    private void sync_ent(JSONObject town, String opt, String msg, String timefield) {
        UpdateDateUtilEx dataUtil = new UpdateDateUtilEx(db,
                SyncActivity.this, user);

        String code = town.optString("code");

        if (code.length() < 8)
            return;
        int start = 0;

        int sum = dataUtil.sum("BEIJIANDANWEI" + code.substring(0, 8), 0, town.optString(timefield), code, opt);
        setMessage("准备" + msg, 0, BARVAL);
        if (sum > 0) {
            while (start < sum) {
                start += 20;
                int bar = (int) (((double) start / (double) sum) * 100);
                if (bar > 100) {
                    bar = 100;
                }
                setMessage("正在" + msg + ":" + bar + "%", bar, BARVAL);

                int rcode = dataUtil.sum("BEIJIANDANWEI" + code.substring(0, 8), 0, town.optString(timefield), code, opt);
                Log.d("rafe rcode", rcode + "异常退出");
                if (rcode < 0) {
                    Log.d("rafe", "异常退出");
                    break;
                }
            }
            setMessage(msg + "完成", 100, BARVAL);
        }


    }

    public String getVersion() {
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {

            return "1";
        }
    }

    private void del_ent(String msg, String table, JSONObject town) {

        UpdateDateUtilEx dataUtil = new UpdateDateUtilEx(db,
                SyncActivity.this, user);
        String maxtime = "";
        String code = "";
        if (town != null) {
            code = town.optString("code");
            table = "BEIJIANDANWEI" + code;
            maxtime = town.optString("ent_delete_time");
        } else {
            maxtime = db.queryEntMaxMotifyTime(table, "DELETETIME", user.getKnowRegion());
        }
        SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyy");
        try {
            if (simpledateformat.parse(maxtime).getYear() < 2000) {
                maxtime = "2016-06-01%2000:00:00";
            }
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            maxtime = "2016-06-01%2000:00:00";
        }
        maxtime = maxtime.replaceAll(" ", "%20");

        Log.d("rafe0705", "正在" + maxtime);
        setMessage("准备" + msg, 0, BARVAL);
        int start = 0;
        Delbean sum = dataUtil.sumDelect(table, start, maxtime, code);
        if (sum.getCount() > 0) {
            while (start < sum.getCount()) {
                start += 20;
                int bar = (int) (((double) start / (double) sum.getCount()) * 100);
                if (bar > 100) {
                    bar = 100;
                }

                Log.d("rafe0705", "正在" + msg + ":" + bar + "%");
                Delbean sum1 = dataUtil.sumDelect(table, start, maxtime, code);
                if (sum1.getCount() < 0) {
                    Log.d("rafe", msg + "异常退出");
                    break;
                }
            }
        }
        setMessage(msg + "完成", 100, BARVAL);


    }

    /**
     * 计划接口
     */

    protected void getPlans() {
        setMessage("正在加载计划", 1, SHOW);

        //		 if(!db.hasTable("MONITOR_PLAN")){
        // 	         db.create( getResources().getString(
        // 				  R.string.table_monitorplan));
        // 	          Log.d("rafe","创建计划表");
        // 	      }
        //
        //		 if(!db.hasTable("MONITOR_PLAN_ENTS")){
        // 	         db.create( getResources().getString(
        // 				  R.string.table_monitorplan_ent));
        // 	          Log.d("rafe","创建计划对象表");
        // 	      }
        //
        Thread planThread = new Thread(new Runnable() {
            @Override
            public void run() {

                optPlan("add", "下载");
                optPlan("modify", "更新");
                optPlan("delete", "删除");

                setMessage("关闭加载条", 1, HIDE);
                setMessage("清除加载条", 1, SYNCPLANCOMP);
            }
        });


        planThread.start();

    }

    private void checkPlan() {
        setMessage("", 1, HIDE);
        //setMessage("",1,SHOWPLANCHECK);
    }

    private void checkPlan__() {
        setMessage("正在加载计划", 1, SHOW);
        new Thread(new Runnable() {
            @Override
            public void run() {
                String maxTime = db.queryMaxMotifyTime("MONITOR_PLAN", "ADDTIME",
                        user.getKnowRegion());
                maxTime = maxTime.replaceAll(" ", "T");
                Log.d("rafe plan maxTime", maxTime);
                UpdateDateUtilEx dataUtil = new UpdateDateUtilEx(db,
                        SyncActivity.this, user);
                JSONObject data = dataUtil.getPlanObject("0", 0, maxTime, "add");
                if (data != null && data.optInt("totalCount", 0) > 0) {
                    setMessage("", 1, HIDE);
                    setMessage("", 1, SHOWPLANCHECK);
                } else {
                    setMessage("", 1, HIDE);
                    checkPlan2();

                }

            }
        }).start();
    }

    private void checkPlan2() {


        setMessage("正在加载计划数据", 1, SHOW);
        new Thread(new Runnable() {
            @Override
            public void run() {
                String maxTime = db.queryMaxMotifyTime("MONITOR_PLAN", "MODIFYTIME",
                        user.getKnowRegion());

                maxTime = maxTime.replaceAll(" ", "T");
                Log.d("rafe plan MODIFYTime", maxTime);
                UpdateDateUtilEx dataUtil = new UpdateDateUtilEx(db,
                        SyncActivity.this, user);
                JSONObject data = dataUtil.getPlanObject("0", 0, maxTime, "modify");
                if (data != null && data.optInt("totalCount", 0) > 0) {
                    setMessage("", 1, HIDE);
                    setMessage("", 1, SHOWPLANCHECK);
                } else {
                    setMessage("", 1, HIDE);
                    checkPlan3();
                }

            }
        }).start();
    }

    private void checkPlan3() {
        setMessage("正在加载基础数据", 1, SHOW);

        new Thread(new Runnable() {
            @Override
            public void run() {

                String maxTime = getPlanDelTime();
                if (maxTime.equals("")) {
                    maxTime = db.queryMaxMotifyTime("MONITOR_PLAN", "MODIFYTIME",
                            user.getKnowRegion());
                    maxTime = maxTime.replaceAll(" ", "T");

                }


                Log.d("rafe plan Delect Time", maxTime);


                UpdateDateUtilEx dataUtil = new UpdateDateUtilEx(db,
                        SyncActivity.this, user);
                JSONObject data = dataUtil.getPlanObject("0", 0, maxTime, "delete");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                maxTime = sdf.format(new Date());
                setPlanDelTime(maxTime.replaceAll(" ", "T"));
                if (data != null && data.optInt("totalCount", 0) > 0) {
                    setMessage("", 1, HIDE);
                    setMessage("", 1, SHOWPLANCHECK);
                } else
                    setMessage("", 1, HIDE);


            }
        }).start();
    }


    private void optPlan(String opt, String msg) {

        String timefield = "ADDTIME";
        if (opt.equals("modify")) {
            timefield = "MODIFYTIME";
        } else if (opt.equals("delect")) {
            timefield = "DELETETIME";

        }
        String maxTime = db.queryMaxMotifyTime("MONITOR_PLAN", timefield,
                user.getKnowRegion());
        maxTime = maxTime.replaceAll(" ", "T");

        UpdateDateUtilEx dataUtil = new UpdateDateUtilEx(db,
                SyncActivity.this, user);
        int start = 0;
        int sum = dataUtil.sumPlan(start, maxTime, opt);
        if (sum > 0) {
            setMessage("正在" + msg + "计划信息 ", 0, BARVAL);
            while (start < sum) {
                start += 10;
                int bar = (int) (((double) start / (double) sum) * 100);
                if (bar > 100) {
                    bar = 100;
                }
                setMessage("正在" + msg + "计划信息:" + bar + "%", bar, BARVAL);
                if (dataUtil.sumPlan(start, maxTime, opt) < 0) {
                    Log.d("rafe", "异常退出");
                    break;
                }
            }
            setMessage(msg + "计划信息完成", 100, BARVAL);

        }


    }
}
